package gui.controlpanel;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.GroupLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JLabel;

import client.controlpanel.Configuration;

@SuppressWarnings("serial")
public class ConfigurationDialog extends JDialog {
	JButton closeButton;
	JComboBox sources;
	JComboBox ports;

	public ConfigurationDialog(final JButton start, final JButton stop) {
		GroupLayout layout = new GroupLayout(getContentPane());
		setLayout(layout);
		final ConfigurationDialog dialog = this;
		final Configuration config = Configuration.getInstance();
		setTitle("Configuration");
		
		JLabel sourcesLabel = new JLabel("Data Source:");
		sources = new JComboBox(config.getAvailableDataSources().toArray());
		sources.setSelectedIndex(config.getAvailableDataSources().indexOf(config.getActiveDataSource().getConfigId()));
		JLabel portsLabel = new JLabel("Communication Port:");
		ports = new JComboBox(config.getAvailablePorts().toArray());
		ports.setSelectedIndex(config.getAvailablePorts().indexOf(config.getPortName()));
		
		closeButton = new JButton();
		closeButton.setText("Close and save");
		closeButton.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				dialog.setVisible(false);
				config.setActiveDataSource(sources.getSelectedItem().toString());
				start.setEnabled(true);
				stop.setEnabled(false);
			
				config.setPortName(ports.getSelectedItem().toString());
			}
		});
		layout.setHorizontalGroup(layout.createParallelGroup(Alignment.CENTER)
				.addComponent(sourcesLabel).addComponent(sources)
				.addComponent(portsLabel).addComponent(ports)
				.addComponent(closeButton));
		layout.setVerticalGroup(layout.createSequentialGroup()
				.addComponent(sourcesLabel).addComponent(sources)
				.addComponent(portsLabel).addComponent(ports)
				.addComponent(closeButton));

		layout.setAutoCreateContainerGaps(true);
		layout.setAutoCreateGaps(true);

		setDefaultCloseOperation(DISPOSE_ON_CLOSE);
	}

}
